/*
 * @lc app=leetcode.cn id=162 lang=typescript
 *
 * [162] 寻找峰值
 */

// @lc code=start
function findPeakElement(nums: number[]): number {
  // 处理边界，返回当前索引的值
  const getNum = (idx: number): number => {
    if (idx < 0 || idx === n) return Number.NEGATIVE_INFINITY;
    return nums[idx];
  };
  // 返回比较结果
  const compare = (idx1: number, idx2: number): number => {
    const a = getNum(idx1);
    const b = getNum(idx2);

    if (a === b) return 0;

    return a < b ? -1 : 1;
  };

  const n = nums.length;
  let head = 0;
  let tail = n - 1;

  while (head <= tail) {
    let mid = head + ((tail - head) >> 1);
    // 符合峰值条件，直接返回
    if (compare(mid - 1, mid) < 0 && compare(mid, mid + 1) > 0) {
      return mid;
    }
    if (compare(mid, mid + 1) < 0) {
      // 当前小于下一个值，表示峰值在后面
      head = mid + 1;
    } else {
      // 峰值在前面
      tail = mid - 1;
    }
  }

  return -1;
}
// @lc code=end
